# FTP2PDM 系统主程序入口
# -*- coding: utf-8 -*-
# 该系统用于Excel文件处理、文件搜索复制、压缩和解压等功能

import sys
import io

# 设置标准输出和错误输出为UTF-8编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

import pandas as pd
import openpyxl
import pyperclip
import docx
import win32clipboard
import zipfile
import os
import shutil
import re
from excel_clipboard import ExcelClipboardManager
from file_search_copy import FileSearchCopyManager

class FTP2PDM:
    def __init__(self):
        """初始化FTP2PDM系统"""
        print("FTP2PDM系统已初始化")
        
    def read_excel(self, file_path):
        """读取Excel文件"""
        try:
            df = pd.read_excel(file_path)
            return df
        except Exception as e:
            print(f"读取Excel文件时出错: {e}")
            return None
    
    def write_excel(self, file_path, data):
        """写入Excel文件"""
        try:
            data.to_excel(file_path, index=False)
            print(f"Excel文件已保存至: {file_path}")
        except Exception as e:
            print(f"写入Excel文件时出错: {e}")
    
    def format_excel(self, file_path):
        """格式化Excel文件"""
        try:
            wb = openpyxl.load_workbook(file_path)
            # 这里可以添加格式化代码
            wb.save(file_path)
            print(f"Excel文件已格式化: {file_path}")
        except Exception as e:
            print(f"格式化Excel文件时出错: {e}")
    
    def search_in_excel(self, file_path, search_term):
        """在Excel文件中搜索内容"""
        try:
            df = pd.read_excel(file_path)
            result = df[df.apply(lambda row: row.astype(str).str.contains(search_term).any(), axis=1)]
            return result
        except Exception as e:
            print(f"在Excel文件中搜索时出错: {e}")
            return None
    
    def get_clipboard_content(self):
        """获取剪贴板内容"""
        try:
            content = pyperclip.paste()
            return content
        except Exception as e:
            print(f"获取剪贴板内容时出错: {e}")
            return None
    
    def search_files(self, search_dir, search_terms):
        """在指定目录中搜索文件"""
        try:
            found_files = []
            for root, dirs, files in os.walk(search_dir):
                for file in files:
                    for term in search_terms:
                        if term in file:
                            found_files.append(os.path.join(root, file))
                            break
            return found_files
        except Exception as e:
            print(f"搜索文件时出错: {e}")
            return []
    
    def copy_files(self, file_list, destination):
        """批量复制文件"""
        try:
            if not os.path.exists(destination):
                os.makedirs(destination)
                
            for file_path in file_list:
                if os.path.exists(file_path):
                    file_name = os.path.basename(file_path)
                    shutil.copy2(file_path, os.path.join(destination, file_name))
                    print(f"已复制: {file_path} -> {destination}")
        except Exception as e:
            print(f"复制文件时出错: {e}")
    
    def zip_files(self, file_list, zip_path):
        """压缩文件为ZIP格式"""
        try:
            with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
                for file_path in file_list:
                    if os.path.exists(file_path):
                        zipf.write(file_path, os.path.basename(file_path))
                        print(f"已添加到压缩文件: {file_path}")
            print(f"压缩文件已创建: {zip_path}")
        except Exception as e:
            print(f"压缩文件时出错: {e}")
    
    def delete_files(self, file_list):
        """删除文件"""
        try:
            for file_path in file_list:
                if os.path.exists(file_path):
                    os.remove(file_path)
                    print(f"已删除: {file_path}")
        except Exception as e:
            print(f"删除文件时出错: {e}")
    
    def copy_excel_selected_cells(self):
        """将Excel中用户选中的单元格值复制到系统剪贴板"""
        try:
            # 创建Excel剪贴板管理器实例
            excel_manager = ExcelClipboardManager()
            
            # 复制选中的单元格值到剪贴板
            success = excel_manager.copy_selected_cells_to_clipboard()
            
            # 关闭连接
            excel_manager.close()
            
            return success
        except Exception as e:
            print(f"复制Excel选中单元格时出错: {e}")
            return False
    
    def copy_excel_selected_cells_as_list(self):
        """将Excel中用户选中的单元格值以列表形式复制到系统剪贴板"""
        try:
            # 创建Excel剪贴板管理器实例
            excel_manager = ExcelClipboardManager()
            
            # 复制选中的单元格值到剪贴板（列表形式）
            success = excel_manager.copy_selected_cells_as_list()
            
            # 关闭连接
            excel_manager.close()
            
            return success
        except Exception as e:
            print(f"以列表形式复制Excel选中单元格时出错: {e}")
            return False
            
    def search_and_copy_files_from_clipboard(self, search_path, target_path, recursive=True, overwrite=False):
        """从剪贴板读取值，搜索并复制文件或文件夹到指定位置"""
        try:
            # 创建文件搜索与复制管理器实例
            file_manager = FileSearchCopyManager()
            
            # 一站式处理：从剪贴板读取值，搜索并复制文件
            success, copied_count = file_manager.process_from_clipboard(search_path, target_path, recursive, overwrite)
            
            if success:
                print(f"成功复制了{copied_count}个文件/文件夹到{target_path}")
            else:
                print(f"复制失败或没有找到匹配的文件")
                
            return success, copied_count
        except Exception as e:
            print(f"搜索并复制文件时出错: {e}")
            return False, 0
            
    def search_files_with_manager(self, search_path, search_patterns=None, recursive=True):
        """使用文件搜索管理器搜索文件"""
        try:
            file_manager = FileSearchCopyManager()
            
            if search_patterns:
                file_manager.set_search_patterns(search_patterns)
            else:
                # 从剪贴板获取搜索模式
                if not file_manager.get_clipboard_values():
                    print("无法从剪贴板获取搜索模式")
                    return []
                file_manager.set_search_patterns()
                
            # 搜索文件
            matched_items = file_manager.search_files(search_path, recursive)
            
            # 提取文件路径
            file_paths = [item[0] for item in matched_items]
            print(f"找到{len(file_paths)}个匹配的文件/文件夹")
            
            return file_paths
        except Exception as e:
            print(f"搜索文件时出错: {e}")
            return []
            
    def copy_items_with_manager(self, item_paths, target_path, overwrite=False):
        """使用文件搜索管理器复制文件或文件夹"""
        try:
            file_manager = FileSearchCopyManager()
            
            # 准备要复制的项目列表
            matched_items = []
            for path in item_paths:
                if os.path.isfile(path):
                    matched_items.append((path, 'file'))
                elif os.path.isdir(path):
                    matched_items.append((path, 'folder'))
            
            # 复制项目
            success, copied_count = file_manager.copy_items(matched_items, target_path, overwrite)
            
            if success:
                print(f"成功复制了{copied_count}个文件/文件夹到{target_path}")
            else:
                print(f"复制失败")
                
            return success, copied_count
        except Exception as e:
            print(f"复制文件时出错: {e}")
            return False, 0

if __name__ == "__main__":
    # 示例用法
    ftp2pdm = FTP2PDM()
    print("系统已启动，请根据需要调用相应功能。")
    
    # 以下是各功能的简单调用示例
    # 1. 读取Excel文件
    # df = ftp2pdm.read_excel("example.xlsx")
    
    # 2. 从剪贴板获取内容并搜索文件
    # clipboard_content = ftp2pdm.get_clipboard_content()
    # if clipboard_content:
    #     search_terms = clipboard_content.split('\n')
    #     found_files = ftp2pdm.search_files("D:\search_dir", search_terms)
    #     ftp2pdm.copy_files(found_files, "D:\destination")
    
    # 3. 压缩文件
    # ftp2pdm.zip_files(found_files, "backup.zip")
    
    # 4. 复制Excel中选中的单元格值到剪贴板
    # ftp2pdm.copy_excel_selected_cells()
    
    # 5. 以列表形式复制Excel中选中的单元格值到剪贴板
    # ftp2pdm.copy_excel_selected_cells_as_list()
    
    # 6. 从剪贴板读取值，搜索并复制文件或文件夹（一站式处理）
    # success, count = ftp2pdm.search_and_copy_files_from_clipboard(
    #     search_path="D:\search_dir",  # 搜索路径
    #     target_path="D:\destination"   # 目标路径
    # )
    
    # 7. 使用文件搜索管理器搜索文件
    # found_files = ftp2pdm.search_files_with_manager(
    #     search_path="D:\search_dir",
    #     search_patterns=["test", "example"],  # 可选，不提供则从剪贴板获取
    #     recursive=True
    # )
    
    # 8. 使用文件搜索管理器复制文件或文件夹
    # if found_files:
    #     success, count = ftp2pdm.copy_items_with_manager(
    #         item_paths=found_files,
    #         target_path="D:\destination"
    #     )